<?php
// 应用公共文件
use TencentCloud\Common\Credential;
use TencentCloud\Common\Exception\TencentCloudSDKException;
use TencentCloud\Ses\V20201002\Models\SendEmailRequest;
use TencentCloud\Ses\V20201002\SesClient;
use TencentCloud\Sms\V20210111\Models\SendSmsRequest;
use TencentCloud\Sms\V20210111\SmsClient;
use think\facade\Cache;
use think\facade\Session;

function decryptPassword($encryptedData)
{
    // 1. 从加密数据中提取IV（前12字节 = 24个十六进制字符）
    $ivHex = substr($encryptedData, 0, 24);
    $iv = hex2bin($ivHex);
    // 2. 提取剩余部分（密文 + 认证标签）
    $ciphertextWithTagHex = substr($encryptedData, 24);
    $ciphertextWithTag = hex2bin($ciphertextWithTagHex);
    // 3. AES-GCM认证标签通常是16字节
    $tagLength = 16;
    $tag = substr($ciphertextWithTag, -$tagLength);
    $ciphertext = substr($ciphertextWithTag, 0, -$tagLength);
    // 4. 生成当前时间戳密钥
    $timestamp = time() * 1000; // 转换为毫秒级，与前端一致
    $keySeed = strval(intval($timestamp / 30000));
    $key = str_pad($keySeed, 16, '0', STR_PAD_LEFT);
    $decrypted = openssl_decrypt($ciphertext, 'aes-128-gcm', $key, OPENSSL_RAW_DATA, $iv, $tag);
    if ($decrypted) return $decrypted;
    $timestampWindow = $timestamp / 1000; // 转换为秒
    $keySeedAttempt = strval(intval((($timestampWindow - 15) * 1000) / 30000));
    if ($keySeedAttempt == $keySeed) $keySeedAttempt = strval(intval((($timestampWindow + 15) * 1000) / 30000));
    $keyAttempt = str_pad($keySeedAttempt, 16, '0', STR_PAD_LEFT);
    $decrypted = openssl_decrypt($ciphertext, 'aes-128-gcm', $keyAttempt, OPENSSL_RAW_DATA, $iv, $tag);
    return $decrypted;
}

function returnJson($code = 0, $msg = 'Success', $data = '', $count = '', $data0 = '')
{
    header('Content-Type:application/json; charset=utf-8');
    $result = ['code' => $code, 'msg' => $msg, 'data' => $data,];
    if ($count != '') {
        $result = ['code' => $code, 'msg' => $msg, 'data' => $data, 'count' => $count];
    }
    if ($data0 != '') {
        $result = ['code' => $code, 'msg' => $msg, 'data' => $data, 'data0' => $data0];
    }
    return json($result);
}

function checkLogin()
{
    $user = Session::get('user');
    if (!$user) {
        header('Content-Type:application/json; charset=utf-8');
        exit(returnJson(-1, '未登录')->getContent());
    }
    return $user;
}

//发送邮件验证码
function sendEmailCode($email, $code)
{
    try {
        $cred = new Credential(env("TencentCloud.SecretId"), env("TencentCloud.SecretKey"));
        $client = new SesClient($cred, "ap-hongkong");

        $req = new SendEmailRequest();
        $params = array("FromEmailAddress" => "SCHUB <system@mail.schub.top>", "Destination" => array($email), "Subject" => "[SCHUB]验证码", "Template" => array("TemplateID" => 136870, "TemplateData" => json_encode(["code" => "$code"])));
        $req->fromJsonString(json_encode($params));
        $resp = $client->SendEmail($req);
        $res_data = json_decode($resp->toJsonString(), true);
        if (isset($res_data['Response']['Error'])) {
            return false;
        }
        return true;
    } catch (TencentCloudSDKException $e) {
        return false;
    }
}

//发送短信验证码
function sendSmsCode($phone, $code)
{
    try {
        $cred = new Credential(env("TencentCloud.SecretId"), "TencentCloud.SecretKey");
        $client = new SmsClient($cred, "ap-beijing");

        $req = new SendSmsRequest();
        $params = array("PhoneNumberSet" => array($phone), "TemplateId" => "2381626", "SmsSdkAppId" => "1400800241", "TemplateParamSet" => array($code));
        $req->fromJsonString(json_encode($params));
        $resp = $client->SendSms($req);
        $res_data = json_decode($resp->toJsonString(), true);
        if (isset($res_data['Response']['Error'])) {
            return false;
        }
        return true;
    } catch (TencentCloudSDKException $e) {
        return false;
    }
}

//图形验证码验证
function checkCaptcha($value)
{
    if (Cache::get($value . "time") and (time() - Cache::get($value . "time") < 60)) return (returnJson(101, msg: "请勿频繁发送", data: ["seconds" => 60 - (time() - Cache::get($value . "time"))])->getContent());
    if (is_array(Session::get('captcha'))) Session::delete('captcha');
    if (!(Session::has('captcha') and (time() - Session::get('captcha') < 5))) return (returnJson(100, msg: "请先验证图形验证码")->getContent());
    return true;
}
